package com.example.casper.jnuexperiment2025.activity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import com.example.casper.jnuexperiment2025.R;

public class BookDetailsActivity extends AppCompatActivity {

    private EditText etBookName, etPrice;
    private Button btnConfirm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_book_edit);

        etBookName = findViewById(R.id.et_book_name);
        etPrice = findViewById(R.id.et_price);
        btnConfirm = findViewById(R.id.btn_confirm);

        // 获取传递过来的数据s
        Intent intent = getIntent();
        boolean isEdit = intent.getBooleanExtra("isEdit", false);

        // 编辑模式
        if (isEdit) {
            String bookName = intent.getStringExtra("bookName");
            double price = intent.getDoubleExtra("price", 0.0);
            if (bookName != null) {
                etBookName.setText(bookName);

            }
            etPrice.setText(String.valueOf(price));
            setTitle("编辑书籍");
        } else {
            setTitle("添加书籍");
        }

        btnConfirm.setOnClickListener(v -> {
            String bookName = etBookName.getText().toString().trim();
            String priceStr = etPrice.getText().toString().trim();

            // 输入验证
            if (bookName.isEmpty()) {
                etBookName.setError("书名不能为空");
                return;
            }

            if (priceStr.isEmpty()) {
                etPrice.setError("价格不能为空");
                return;
            }

            try {
                double price = Double.parseDouble(priceStr);

                Intent resultIntent = new Intent();
                resultIntent.putExtra("bookName", bookName);
                resultIntent.putExtra("price", price);
                resultIntent.putExtra("isEdit", isEdit);

                setResult(RESULT_OK, resultIntent);
                finish();

            } catch (NumberFormatException e) {
                etPrice.setError("请输入有效的价格");
            }
        });
    }
}